<template>
  <div v-if="subComment != null" class="c-bg-sgray c-pb120">
    <shop-comment-com :subComment="subComment" @showStars="showStars" :showType="1" :showExtraOperation="showExtraOperation"></shop-comment-com>
    <div class="c-bg-white c-pf c-p-l0 c-p-r0 c-pv24 c-p-b0 c-ph24 c-pz10">
      <div class="theme-bg c-br36 c-flex-row c-aligni-center c-justify-center c-fc-white c-mlr-auto c-fs24 c-lh34 c-ww600 c-hh64" @click="addComment(type)">提交评价
        <span class="c-fs22 c-ml10">{{type == 2 || type == 3 ? '(仅支持修改一次)' : ''}}</span>
      </div>
    </div>
  </div>
</template>
<script>
import { utilJs } from "@/utils/common.js";
import ShopCommentCom from "@/components/templates/shopCommentCom.vue";
import { mapState } from 'vuex';
let isFromOrderList = false;
let isFromAllOrderList = false;
export default {
  name: 'AddShopComment',
  components: {
    ShopCommentCom
  },
  data() {
    return {
      id: '', // 评价id
      goId: '', // 订单id,针对订单评论增加的id
      isWeiXin: true,
      type: 1, // 1添加评价、2是修改订单评价详情、3是修改评价详情
      goodsInfo: null, // 商品基本信息
      subComment: [], // 评价信息
      isExtra: 0, // 追加评论
    }
  },
  computed: {
    ...mapState({
      orderList: state => state.oem_store.orderList,
      allOrderList: state => state.oem_store.allOrderList
    }),
  },
  beforeRouteEnter(to, from, next) {
    if (from.path == '/mall/mallOrder/orderList') {
      isFromOrderList = true;
    } else if (from.path == '/member/myOrder/allOrderList') {
      isFromAllOrderList = true;
    } else if (from.path == '/mall/mallOrder/orderDetail') {
      isFromOrderList = true;
      isFromAllOrderList = true;
    }
    next()
  },
  methods: {
    // 获取订单评价信息
    getOrderInfo() {
      let that = this;
      let data = {
        goId: that.goId
      }
      utilJs.postMethod(`${global.apiurl}goodsOrders/subOrderPage`, data,
        res => {
          that.goodsInfo = res.goods;
          // 初始化数据
          that.goodsInfo.forEach((item, index) => {
            let single = {
              avatar: item.avatar,
              goodsName: item.goodsName,
              subSpecs: item.subSpecs,
              goId: Number(that.goId),
              godId: item.godId,
              mgId: item.mgId,
              gsiiId: item.gsiiId,
              orderNo: item.mgId,
              starRank: 5,
              words: '',
              pictures: [],
              isAnonymous: 0,
              extra: that.isExtra == 0 ? null : {
                extraWords: '',
                extraPictures: [],
              }
            }
            that.subComment.push(single);
          })
          if (that.isExtra == 1) {
            let mgId = that.$route.query.mgId ? that.$route.query.mgId : '';
            let gsiiId = that.$route.query.gsiiId ? that.$route.query.gsiiId : '';
            if (gsiiId.length == '') {
              that.subComment = that.subComment.filter(item => item.mgId == mgId);
              return
            }
            that.subComment = that.subComment.filter(item => item.mgId == mgId && item.gsiiId == gsiiId);
          }
        }
      )
    },
    addComment(type) {
      if (type == 1) {
        if (this.isExtra == 0) {
          // 提交评价信息
          let comments = [];
          this.subComment.forEach((item, index) => {
            let single = {
              goId: Number(item.goId),
              mgId: item.mgId,
              orderNo: item.mgId,
              godId: item.godId,
              starRank: item.starRank,
              words: item.words,
              pictures: item.pictures,
              isAnonymous: item.isAnonymous,
            }
            comments.push(single);
          })
          let data = {
            'commentArr': comments
          }
          utilJs.postMethod(`${global.apiurl}goods/addComment`, data,
            res => {
              if (res.isBan == 1) {
                this.$cjConfirm({
                  showCancelButton: false,
                  title: '温馨提示',
                  message: `暂无权限评论，请联系管理员~`,
                });
                return
              }
              this.$showCjToast({
                text: '评价成功',
                type: 'success'
              });
              this.$routerGo(this, "replace", {
                path: '/mall/shopComments/shopCommentDetail',
                query: ({
                  id: this.goId, // id为goId
                  type: 1
                })
              })
              this.updateStore(); // 局部更新订单列表也得评价按钮隐藏
            }
          )
        } else {
          // 提交追加评价信息
          this.addCommentExtra();
        }
      } else if (type == 2 || type == 3) {
        // 修改追评信息
        if (this.subComment[0].extra != null) {
          this.addCommentExtra();
        } else { // 修改评价信息
          let data = {
            starRank: this.subComment[0].starRank,
            words: this.subComment[0].words,
            pictures: this.subComment[0].pictures,
            isAnonymous: this.subComment[0].isAnonymous
          }
          utilJs.postMethod(`${global.apiurl}goods/updateComment/` + this.id, data,
            res => {
              if (res.isBan == 1) {
                this.$cjConfirm({
                  showCancelButton: false,
                  title: '温馨提示',
                  message: `暂无权限评论，请联系管理员~`,
                });
                return
              }
              this.$showCjToast({
                text: '修改成功',
                type: 'success'
              });
              this.$routerGo(this, "replace", {
                path: '/mall/shopComments/shopCommentDetail',
                query: ({
                  id: this.id,
                  type: 2
                }) //1是订单评价详情2是独立评价详情
              })
            }
          )
        }
      }
    },
    // 处理追加评论
    addCommentExtra() {
      if (this.subComment[0] && this.subComment[0].extra == null) return
      let data = {
        extraWords: this.subComment[0].extra.extraWords,
        extraPictures: this.subComment[0].extra.extraPictures,
      }
      data.mcId = this.subComment[0].id || this.id;
      if (this.subComment[0].extra.mceId) data.mceId = this.subComment[0].extra.mceId;
      utilJs.postMethod(`${global.apiurl}goods/addCommentExtra`, data,
        res => {
          if (res.isBan == 1) {
            this.$cjConfirm({
              showCancelButton: false,
              title: '温馨提示',
              message: `暂无权限评论，请联系管理员~`,
            });
            return
          }
          this.$showCjToast({
            text: '追评成功',
            type: 'success'
          });
          this.$routerGo(this, "replace", {
            path: '/mall/shopComments/shopCommentDetail',
            query: ({
              id: this.id, // id为goId
              type: 2
            })
          })
        }
      )
    },
    // 局部更新订单列表也得评价按钮隐藏
    updateStore() {
      let orderType = this.$route.query.orderType || -1; // 订单列表的type -1全部 0待付款 1待发货 2待收货 3待评价
      if (isFromOrderList) {
        let orderList = this.orderList;
        if (orderType == 3) {
          sessionStorage.setItem('filterOrder', true);
          let list = orderList.filter(item => item.goId != this.goId);
          this.$store.commit('updateOrderList', list);
          isFromOrderList = false;
          return
        }
        orderList.forEach((item, index) => {
          if (item.goId == this.goId) {
            this.$set(orderList[index], 'isCommented', 1)
          }
        })
        this.$store.commit('updateOrderList', orderList);
        isFromOrderList = false;
      }
      if (isFromAllOrderList) {
        let allOrderList = this.allOrderList;
        if (orderType == 3) {
          sessionStorage.setItem('filterOrder', true);
          let list = allOrderList.filter(item => item.goId != this.goId);
          this.$store.commit('updateAllOrderList', list);
          isFromAllOrderList = false;
          return
        }
        allOrderList.forEach((item, index) => {
          if (item.goId == this.goId) {
            this.$set(allOrderList[index], 'isCommented', 1)
          }
        })
        this.$store.commit('updateAllOrderList', allOrderList);
        isFromAllOrderList = false;
      }
    },
    //分享
    wechatShare: function () {
      let shareUrl =
        window.location.href.split("#")[0] +
        "#/?refereeId=" +
        localStorage.getItem("userId");
      utilJs.wechatConfig(shareUrl, "", "", "", function () { }, true);
    },
    //手机端分享
    appShare: function () {
      var shareUrl =
        window.location.href.split("#")[0] +
        "#/?refereeId=" +
        localStorage.getItem("userId");
      utilJs.appShareTrue("", "", shareUrl, "");
    }
  },
  activated() {
    this.type = this.$route.query.type ? this.$route.query.type : '';
    this.goId = this.$route.query.goId ? this.$route.query.goId : '';
    this.id = this.$route.query.id ? this.$route.query.id : '';
    this.isExtra = this.$route.query.isExtra ? this.$route.query.isExtra * 1 : 0;
    this.goodsInfo = null;
    this.subComment = [];
    if (this.type == 1) {
      this.getOrderInfo();
      this.isExtra == 0 ? setDocumentTitle("发表评价") : setDocumentTitle("追加评价");
    } else {
      setDocumentTitle("修改评价");
      this.subComment = JSON.parse(localStorage.getItem('commentDetail'))
      this.subComment.forEach((item, index) => {
        let createTime = item.createdAt.split(" ");
        this.$set(this.subComment[index], 'createdAt', createTime[0]);
      })
    }
    this.wechatShare();
  },
  deactivated() {
  }
}
</script>